package csc.daonjpa.java.controller;

import java.util.Date;
import java.util.List;

import javax.persistence.PersistenceException;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import csc.daonjpa.java.domain.Account;
import csc.daonjpa.java.service.BankService;

/**
 * This controller handles account related actions
 * 
 * @author nvu3
 * 
 */
@Controller
public class AccountController {
	private static final Logger LOG = Logger.getLogger(AccountController.class);
	private BankService bankService;

	public BankService getBankService() {
		return bankService;
	}

	@Autowired
	public void setBankService(BankService bankService) {
		this.bankService = bankService;
	}

	/**
	 * Adds account to DB
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/createAccount")
	public String addAccount(HttpServletRequest request, Model model) {
		// Read account info from request and save into Account object
		String accountType = request.getParameter("accountType");
		String accountName = request.getParameter("accountName");
		String accountNumber = request.getParameter("accountNumber");
		Date now = new Date();
		Account account = new Account(accountNumber, accountName, accountType, now, now);
		try {
			// Save account to DB
			bankService.addAccount(account);
			model.addAttribute("successMessage",
					"Added new account successfully");
		} catch (PersistenceException ex) {
			if (ex.getCause() instanceof ConstraintViolationException) {
				model.addAttribute("errorMessage", "Duplicated account found");
			} else {
				model.addAttribute("errorMessage", "Error adding new account");
			}
			LOG.error("Error found adding an account", ex);
			throw ex;
		} catch (Exception e) {
			LOG.error("General Error found adding an account", e);
			throw e;
		}
		
		return "forward:/listAccount";
	}

	@RequestMapping(value = "/listAccount")
	public ModelAndView getAccountList(Model model) {

		// Get the list of all accounts from DB
		List<Account> accountList = bankService.getAccounts();

		ModelAndView modelAndView = new ModelAndView("accountList");
		modelAndView.addObject("listAccount", accountList);
		return modelAndView;
	}
	
	@ExceptionHandler(Exception.class)
	public ModelAndView handleAllException(Exception ex) {
 
		ModelAndView model = new ModelAndView("accountList");
		model.addObject("errorMessage", "Exception occurred");
 
		return model;
	}
}
